<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(0);
header('Content-Type: text/html; charset=utf-8');

class Home extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->helper('html');
        $this->load->library('session');
        $this->load->model('users_model');
        $this->load->model('crud_model');
        $this->load->model('admin_category_model');
        $this->load->model('admin_product_model');
        $this->load->library('../controllers/crud');
        $this->load->library("pagination");
    }
	public function index()
	{
        $this->emptyAdminLink();
        $data['category'] = $this->getCategory();
        $this->load->view('head');
        $this->load->view('header');
        $this->load->view('navbar');
        $this->load->view('home', $data);
        $this->load->view('footer');
	}

    public function emptyAdminLink()
    {
        $this->session->set_userdata('linkAdmin', '');
    }

    public function getCategory()
    {
        $dbCategories = $this->admin_category_model->getCategories();
        $menu = array(
            'items' => array(),
            'parents' => array()
        );
        foreach($dbCategories as $cat){
            $menu['items'][$cat['id']] = $cat;
            // Creates entry into parents array. Parents array contains a list of all items with     children
            $menu['parents'][$cat['parentid']][] = $cat['id'];
        }

        $data = $this->buildCategory(0, $menu);
        return $data;
    }

    public function buildCategory($parent, $menu)
    {
        $html = "";
        if (isset($menu['parents'][$parent]))
        {
            $html .= "<ul class='dropdown-menu'>";
            foreach ($menu['parents'][$parent] as $itemId)
            {
                if(!isset($menu['parents'][$itemId]))
                {
                    //IF MENU DONT HAVE SUBMENU
                    $html .= "<li class='menu-item list-unstyled'>
                    <a style='cursor: pointer' onclick='getCategoryDetail(".$menu['items'][$itemId]['id']."); getProductCategoryDetail(".$menu['items'][$itemId]['id'].")' tabindex='-1'>".$menu['items'][$itemId]['name']."</a>
                    </li>";
                }
                if(isset($menu['parents'][$itemId]))
                {
                    //IF MENU HAS SUBMENU
                    $html .= "<li class='menu-item dropdown dropdown-submenu list-unstyled'>
                    <a style='cursor: pointer' onclick='getCategoryDetail(".$menu['items'][$itemId]['id']."); getProductCategoryDetail(".$menu['items'][$itemId]['id'].")' tabindex='-1'>".$menu['items'][$itemId]['name']."</a>";
                    $html .= $this->buildCategory($itemId, $menu);
                    $html .= "</li>";
                }
            }
            $html .= "</ul>";
        }
        return $html;
    }

    public function getCategoryDetail()
    {
        $id = $this->input->post('id', true);
        $field = "*, ca.description AS caDes";
        $table = "category AS ca";
        $condition1 = array(
            'ca.id' => $id,
        );
        $condition2 = "ca.active = 1 AND ca.flag = 0";
        $data['info'] = $this->crud_model->select($field, $table, $condition1, $condition2);
        $this->load->view('category/view', $data);
    }

    public function setChoosenCategory()
    {
        $id = $this->input->post('id', true);
        echo $this->crud->setSession("choosenCategoryHome", $id);
    }

    public function getProductCategoryDetail($start_from = 0)
    {
        $id = $this->session->userdata('choosenCategoryHome');
        $field = "*, pr.description AS prDes";
        $table = "product AS pr";
        $condition1 = array(
            'pr.id_category' => $id,
        );
        $condition2 = "pr.active = 1 AND pr.flag = 0";

        $per_page = 4;
        $config = array();
        $config["base_url"] = base_url() . "/home/getProductCategoryDetail/";
        $config["total_rows"] = $this->crud_model->selectNumOfPagination($field, $table, $condition1, $condition2);
        $config["per_page"] = $per_page;
        $config["uri_segment"] = 3;
        $config['full_tag_open'] = '<ul>';
        $config['full_tag_close'] = '</ul>';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="active">';
        $config['cur_tag_close'] = '</li> ';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li> ';
        $config['next_link'] = 'Next';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['prev_link'] = 'Prev';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li> ';
        $choice = $config["total_rows"] / $config["per_page"];
        $config["num_links"] = round($choice);
        $config['use_page_numbers'] = TRUE;
        $start = $per_page * ($start_from-1);
        if($start < 0){
            $start = 0;
        }
        $data['info'] = $this->crud_model->selectPagination($per_page, $start, $field, $table, $condition1, $condition2);

        $this->load->view('product/view', $data);
    }

    public function getPage()
    {
        $id = $this->session->userdata('choosenCategoryHome');
        $field = "*, pr.description AS prDes";
        $table = "product AS pr";
        $condition1 = array(
            'pr.id_category' => $id,
        );
        $condition2 = "pr.active = 1 AND pr.flag = 0";

        $result = $this->crud_model->selectNumOfPagination($field, $table, $condition1, $condition2);
        $data['num_links'] = $result/4;
        $this->load->view('product/page', $data);
    }

    public function view($id, $title){
        $data['info'] = $this->crud_model->selectID($id, "product");
        $data['rate'] = $this->get_currency("USD", "VND", 1);
        if($data['info'][active] == 0 || empty($data['info'])){
            $this->load->view('head');
            $this->load->view('product/deny');
        }
        else{
            $this->load->view('head');
            $this->load->view('header');
            $this->load->view('navbar');
            $this->load->view('product/viewDetail', $data);
            $this->load->view('footer');
        }
    }

    public function relatedProduct(){
        $id = $this->input->post('id', true);
        $id_category = $this->input->post('id_category', true);
        $data['info'] = $this->admin_product_model->getRelatedProduct($id, $id_category);
        $this->load->view('product/view', $data);
    }

    //<---------------- shopping cart --------------------->//
    public function cart(){
        $data['totalMoney'] = $this->totalMoney(0);
        $data['rate'] = $this->get_currency("USD", "VND", 1);
        $this->load->view('head');
        $this->load->view('header');
        $this->load->view('navbar');
        $this->load->view('cart', $data);
        $this->load->view('footer');
    }

    public function getTableCartManager($start_from = 0)
    {
        $myArr = $this->getShoppingCart();
        $idProducts = $this->getInfoProductCart($myArr, 0);
        $condition1 = "id IN "."(".implode(",", $idProducts).")";
        $condition2 = "pr.active = 1 AND pr.flag = 0";

        $per_page = 4;
        $config = array();
        $config["base_url"] = base_url() . "/home/getTableCartManager/";
        if(!empty($idProducts)){
            $config["total_rows"] = $this->crud_model->selectNumOfPagination("*", "product AS pr", $condition1, $condition2);
        }
        $config["per_page"] = $per_page;
        $config["uri_segment"] = 3;
        $config['full_tag_open'] = '<ul>';
        $config['full_tag_close'] = '</ul>';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="active">';
        $config['cur_tag_close'] = '</li> ';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li> ';
        $config['next_link'] = 'Next';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['prev_link'] = 'Prev';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li> ';
        $choice = $config["total_rows"] / $config["per_page"];
        $config["num_links"] = round($choice);
        $config['use_page_numbers'] = TRUE;
        $start = $per_page * ($start_from-1);
        if($start < 0){
            $start = 0;
        }

        $data['rate'] = $this->get_currency("USD", "VND", 1);
        $quantity = $this->getInfoProductCart($myArr, 1);
        if(!empty($idProducts)){
            $data['cartList'] = $this->crud_model->selectPagination($per_page, $start, "*", "product AS pr", $condition1, $condition2);
        }
        //them truong quantity
        foreach($data['cartList'] as $objCartList){
            $objCartList->quantity = $quantity[$objCartList->id];
        }
        $this->load->view('cart/cart_list', $data);
    }

    public function getPageCart()
    {
        $myArr = $this->getShoppingCart();
        $idProducts = $this->getInfoProductCart($myArr, 0);
        $condition1 = "id IN "."(".implode(",", $idProducts).")";
        $condition2 = "pr.active = 1 AND pr.flag = 0";

        $result = $this->crud_model->selectNumOfPagination("*", "product AS pr", $condition1, $condition2);
        $data['num_links'] = $result/4;
        $this->load->view('cart/page', $data);
    }

    public function updateProductCart(){
        $id = $this->input->post('id', true);
        $oldQuantity = $this->input->post('oldQuantity', true);
        $newQuantity = $this->input->post('newQuantity', true);
        $oldString = $id."_".$oldQuantity;
        $newString = $id."_".$newQuantity;
        $data = $this->session->userdata('shoppingCart');
        $dataAfter = str_replace($oldString, $newString, $data);
        $result = $this->crud->setSession('shoppingCart', $dataAfter);
        if($result != ''){
            $num = 0;
            $myArr = explode(", ", $result);
            foreach($myArr as $objMyArr){
                if($objMyArr != ""){
                    $myArrInfo = explode("_", $objMyArr);
                    $num += $myArrInfo[1];
                }
            }
            echo $this->crud->setSession('numOfProductsCart', $num);
        }
        else{
            echo "error";
        }
    }

    public function deleteProductCart(){
        $id = $this->input->post('id', true);
        $quantity = $this->input->post('quantity', true);
        $string = $id."_".$quantity;
        $data = $this->getShoppingCart();
        unset($data[array_search($string, $data)]);
        if(!empty($data)){
            $result = $this->setInfoCart($data);
            if($result != ''){
                $num = $this->session->userdata('numOfProductsCart')-$quantity;
                echo $this->crud->setSession('numOfProductsCart', $num);
            }
            else{
                echo "error";
            }
        }
        else{
            $value = $this->crud->emptySession('shoppingCart');
            if($value == ''){
                $info = $this->crud->emptySession('numOfProductsCart');
                if($info == ''){
                    echo 0;
                }
                else{
                    echo "error";
                }
            }
            else{
                echo "error";
            }
        }
    }

    public function setNumOfProductsCart(){
        $id = $this->input->post('id', true);
        $quantity = $this->input->post('quantity', true);
        $result = $this->insertCart($id, $quantity);
        $num = $this->session->userdata('numOfProductsCart')+$quantity;
        echo $this->crud->setSession('numOfProductsCart', $num);
    }

    public function insertCart($id, $quantity){
        $data = $id."_".$quantity.", ";

        if($this->session->userdata('shoppingCart') == ''){
            return $this->crud->setSession('shoppingCart', $data);
        }
        else{
            $string = $this->session->userdata('shoppingCart');
            $string .= $id."_".$quantity.", ";
            $value = $this->crud->setSession('shoppingCart', $string);
            return $value;
        }
    }

    public function setInfoCart($currentCart){
        $value = "";
        foreach($currentCart as $objCurrentCart){
            $value .= $objCurrentCart.", ";
        }
//        $valueAfter = substr($value, 0, strlen($value)-2); //3 tham so
        return $this->crud->setSession('shoppingCart', $value);
    }

    public function totalMoney($k){
        $data = $this->getShoppingCart();
        $total = 0;
        for($i = 0; $i < count($data); $i++){
            $myObjArr = explode("_", $data[$i]);
            if($myObjArr[0] != ""){
                $result = $this->crud_model->selectID($myObjArr[0], "product");
                $amount = $myObjArr[1];
                $price = $result[product_price1];
                $unit = $result[price_unit];
                if($unit == "USD"){
                    $rate = $this->get_currency("USD", "VND", 1);
                    $total += $amount*$price*$rate;
                }
                else{
                    $total += $amount*$price;
                }
            }
        }
        if($k == 1){
            echo number_format($total);
        }
        return number_format($total);
    }

    public function get_currency($from_Currency, $to_Currency, $amount) {
        $amount = urlencode($amount);
        $from_Currency = urlencode($from_Currency);
        $to_Currency = urlencode($to_Currency);

        $url = "http://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency";

        $ch = curl_init();
        $timeout = 0;
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt ($ch, CURLOPT_USERAGENT,
            "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $rawdata = curl_exec($ch);
        curl_close($ch);
        $data = explode('bld>', $rawdata);
        $data = explode($to_Currency, $data[1]);

        return round($data[0], 2);
    }

    public function getShoppingCart(){
        $value = $this->session->userdata('shoppingCart');
        $data = substr($value, 0, strlen($value)-2); //cat chuoi ", " o cuoi cung
        if($data == ""){
            return 0;
        }
        $myArr = explode(", ", $data);
        $myArrAfter = array();
        for($i = 0; $i < count($myArr); $i++){
            $myArrInfo1 = explode("_", $myArr[$i]);
            $total = $myArrInfo1[1];
            for($j = $i + 1; $j < count($myArr); $j++){
                $myArrInfo2 = explode("_", $myArr[$j]);
                if($myArrInfo1[0] == $myArrInfo2[0]){
                    $total += $myArrInfo2[1];
                }
            }
            $value = $myArrInfo1[0]."_".$total;
            array_push($myArrAfter, $value);
        }
        unset($myArrAfter[count($myArrAfter)]);
        if(count($myArrAfter) > 1){
            return $this->convertArray($myArrAfter);
        }
        else{
            return $myArrAfter;
        }
    }

    public function convertArray($arr){
        $replaceString = array();
        for($i = 0; $i < count($arr); $i++){
            $myArrInfo1 = explode("_", $arr[$i]);
            for($j = $i + 1; $j < count($arr); $j++){
                $myArrInfo2 = explode("_", $arr[$j]);
                if($myArrInfo1[0] == $myArrInfo2[0]){
                    $string = $j;
                    array_push($replaceString, $string);
                }
            }
        }
        foreach($replaceString as $objReplaceString){
            unset($arr[$objReplaceString]);
        }
        $array = array_values(array_filter($arr)); //sap xep lai index cua mang
//        unset($array[count($array)]);
        return $array;
    }

    public function getInfoProductCart($arr, $condition){
        $myArr = array();
        foreach($arr as $objArr){
            $myArrInfo = explode("_", $objArr);
            if($condition == 0){
                array_push($myArr, $myArrInfo[0]);
            }
            else{
                $id = $myArrInfo[0];
                $myArr[$id] = $myArrInfo[1];
            }
        }
        return $myArr;
    }

    public function sessionTest(){
        echo $this->session->userdata('shoppingCart');
    }
}